package cn.qxq1.exception;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangying
 * @date 2020-04-27
 * @description
 */
@ControllerAdvice
public class MyControllerAdvice {

    //    @ExceptionHandler(value = Exception.class)
//    public ModelAndView handleException(Exception e){
//        System.out.println(e.getMessage());
//        if (e instanceof NoHandlerFoundException) {
//            System.out.println("-------404 NoHandlerFoundException------");
//            return new ModelAndView("redirect:/404.html");
//        }
//        return new ModelAndView("redirect:/404-post");
//    }

//    @ExceptionHandler(value = Exception.class)
//    @ResponseBody
//    public String handleException(Exception e) {
//        System.out.println(e.getMessage());
//        if (e instanceof NoHandlerFoundException) {
//            System.out.println("-------404 NoHandlerFoundException------");
//            return "404 result";
//        }
//        return "其他异常哦";
//    }

    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String notFoundException() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("msg", "not found");
        return JSON.toJSONString(map);
    }
}
